<template>
  <div>
    <div class="write" v-if="!mobieType">
    <h1 class="title">开始您的创作 <img class="horse" src="../assets/img/horse.png" alt=""></h1>

    <div class="form">
      <el-form ref="form" :model="form" label-width="80px">
        <el-row>
          <el-col :span="14">
            <el-form-item label="文章标题" style="width: 85%;">
              <el-input v-model="form.title"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="文章分类">
              <el-select v-model="form.category" placeholder="请选择文章分类">
                <el-option v-for="item in categoryOptions" :key="item.id" :label="item.title"
                  :value="item.title"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="文章简介" style="width: 80%;">
          <el-input type="textarea" :rows="1" v-model="form.summary"></el-input>
        </el-form-item>

        <el-form-item label="背景图片">
          <el-upload class="avatar-uploader" :action="uploadUrl()" :data="{ 'id': form.id }" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>

    <div class="mavonEditor">
      <mavon-editor class="edit" ref="md" v-model="text" v-if="showMarkdown" font-size="18px" :scroll-style="true"
        box-shadow-style="0 2px 12px 0 rgba(0,0,5,0.3)" toolbars-background="#A2A5B8" :subfield="false"
        placeholder="开始您的创作..." codeStyle="shades-of-purple" :toolbars="markdownOption" @change="changeMavon" />

      <mavon-editor class="preview" v-model="text" v-if="showMarkdown" font-size="18px"
        box-shadow-style="0 2px 12px 0 rgba(0,0,5,0.3)" toolbars-background="#E0DBD4" :subfield="false"
        placeholder="开始您的创作..." codeStyle="paraiso-light" :toolbars="markdownOption" :editable="false"
        defaultOpen="preview" />
    </div>

    <button @click="submit" class="submit">{{ id ? '一键修改' : '一键发布' }}</button>
    </div>
    <div class="write-mobie" v-else>
      小主，您的设备不支持创作哦，还请移到pc端进行操作
    </div>
  </div>
</template>

<script>
import { fetchCategory, fetchPostArticle, fetchArticle, fetchGetImgs, fetchUpdateArticle } from '../api';
export default {
  data() {
    return {
      id: '',
      form: {
        id: Date.now(),
        title: "",
        summary: "",
        category: "",
        pubTime: "",
        render: "",
        content: "",
        banner: "",
        publisher:this.$store.state.userInfo?.username,
        publisherId:this.$store.state.userInfo?.id
      },
      text: '',
      imageUrl: '',         // 图片加载
      categoryOptions: [],   // 文章分类
      showMarkdown: false,  // 是否显示markdown编辑器
      markdownOption: {     // markdown编辑器配置
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        // imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        // fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        // save: true, // 保存（触发events中的save事件）
        navigation: true, // 导航目录
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        // subfield: true, // 单双栏模式
        // preview: true, // 预览
      },
      acticleImgUrl: process.env.VUE_APP_BASE_URL + "/articleImg",    // 文章图片上传地址
      mobieType:false
    }
  },
  created() {
    const width = document.documentElement.clientWidth || document.body.clientWidth;
    if (width < 900) {
      this.mobieType = true
    }
  },
  mounted() {
    setTimeout(() => {
      this.showMarkdown = true;
    }, 1500);
    this.getCategory();
    this.id = this.$route.query.id || ''
    if (this.id) {
      fetchArticle(this.$route.query.id).then(res => {
        for (let k in this.form) {
          this.form[k] = res[k]
        }
        setTimeout(() => {
          this.text = res.render
        }, 1500);
        this.getBanner(res.banner)
      })
    }

  },
  methods: {
    getCategory() {
      fetchCategory().then(res => {
        this.categoryOptions = res
      })
    },
    submit() {
      if (this.$store.state.userInfo.permission === undefined || this.$store.state.userInfo.permission > 2) return this.$message.error('您没有发布的权限哦')

      if (!this.validate()) return
      this.form.pubTime = Date.now()
      if (this.id) {
        fetchUpdateArticle(this.form).then(res => {
          if (res == '修改成功') {
            this.$message.success("修改成功")
            this.$router.push("/article/" + this.form.id)
          }
        })
      } else {
        fetchPostArticle(this.form).then(res => {
          if (res == '添加成功') {
            this.$message.success("发布成功")
            this.$router.push("/article/" + this.form.id)
          }
        })
      }
    },
    handleAvatarSuccess(res, file) {
      this.form.banner = res
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isImg = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt4M = file.size / 1024 / 1024 < 4;

      if (!isImg) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt4M) {
        this.$message.error('上传头像图片大小不能超过 4MB!');
      }
      return isImg && isLt4M;
    },
    uploadUrl() {
      return this.acticleImgUrl;
    },
    changeMavon(val, render) {
      this.form.render = val
      this.form.content = render
    },
    getBanner(val) {
      fetchGetImgs([val]).then(res => {
        this.imageUrl = 'data:image/png;base64,' + res[0]
      })
    },
    validate() {
      if (this.form.title == ''){
        this.$message.error('请输入文章标题')
        return false
      }
      if (this.form.summary == ''){
        this.$message.error('请输入文章简介')
        return false
      }
      if (this.form.category == ''){
        this.$message.error('请选择文章分类')
        return false
      }
      if (this.form.banner == ''){
        this.$message.error('请上传文章封面')
        return false
      }
      if (this.form.content == ''){
        this.$message.error('请输入文章内容')
        return false
      }
      return true
    }
  }
}
</script>

<style scoped lang="less">
.write {
  // 写文章的页面
  width: 100%;
  height: 100%;
  // background-color: #f6f6;
  padding: 0 120px;
  margin-top: 100px;
}

.write .title {
  font-size: 30px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #6f6f6f;
  text-align: center;
}

.horse {
  width: 50px;
  height: 50px;
  vertical-align: center;
  transform: translateY(10px);
}

.mavonEditor {
  display: flex;
}

.edit {
  margin-right: 20px;
  flex: 1;
  min-height: 600px;
}

.preview {
  flex: 1;
  min-height: 600px;
}

.submit {
  width: 200px;
  height: 80px;
  margin-left: 50%;
  transform: translateX(-50%);
  margin-top: 20px;
  border-radius: 40px;
  border: none;
  color: #fff;
  font-size: 20px;
  font-weight: 500;
  background-color: #2f3039;

  &:hover {
    box-shadow: #2f3039 0 0 10px;
  }
}

.form {
  background-color: #a8d3f8;
  border-radius: 5px;
  padding-left: 40px;
  box-shadow: #2f3039 0 0 10px;
  padding-top: 20px;
}

/deep/ .el-form-item__label {
  color: #fff;
  padding-right: 20px;
  font-size: 14px;
  font-weight: 600;
}

/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #E2A9A1;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background-color: #fff;
}

/deep/ .el-switch.is-checked .el-switch__core {
  border-color: #E2A9A1;
  background-color: #C07B9A;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.write-mobie{
  width: 100%;
  height: 100%;
  padding: 0 30px;
  margin-top: 300px;
}
</style>